// 摄像头标记相关的组合式函数
import { ref, computed } from 'vue'
import * as Cesium from 'cesium'
import { useCameraStore } from '@/store/modules/camera'
import { createCamera } from '@/api/camera'

export function useCameraMarkers(cesiumUtils, videoPlayer) {
    const cameraStore = useCameraStore()

    // 响应式数据
    const cameraList3D = ref([])
    const selectedCamera = ref(null)
    const showCameraInfo = ref(false)
    const isPanelCollapsed = ref(false)

    // 新增摄像头相关
    const showAddCameraDialog = ref(false)
    const isAddingCameraMode = ref(false)
    const isAddingCamera = ref(false)
    const selectedPosition = ref(null)
    const nameCheckMessage = ref(null)
    const newCameraForm = ref({
        name: '',
        location: '',
        rtsp_url: '',
        wvp_device_id: '',
        wvp_channel_id: '',
        description: '',
        ai_enabled: false
    })

    // 编辑摄像头相关
    const isEditingCamera = ref(false)
    const editingCameraId = ref(null)

    // 计算属性：是否可以保存摄像头
    const canSaveCamera = computed(() => {
        return newCameraForm.value.name.trim() &&
            newCameraForm.value.rtsp_url.trim() &&
            selectedPosition.value &&
            (!nameCheckMessage.value || nameCheckMessage.value.type !== 'error')
    })

    // 从API获取摄像头数据
    const loadCamerasFromAPI = async () => {
        try {
            cesiumUtils.isLoading.value = true
            cesiumUtils.loadingText.value = '正在加载摄像头数据...'
            const cameras3D = await cameraStore.fetchAllCamerasFor3D()
            cameraList3D.value = cameras3D
            console.log('摄像头数据已从API加载:', cameras3D.length, '个摄像头')
            return cameras3D
        } catch (error) {
            console.error('加载摄像头数据失败:', error)
            cesiumUtils.showError('无法加载摄像头数据，请刷新页面重试')
            cameraList3D.value = []
            return []
        } finally {
            cesiumUtils.isLoading.value = false
        }
    }

    // 右键菜单相关状态
    const showContextMenu = ref(false)
    const contextMenuPosition = ref({ x: 0, y: 0 })
    const contextMenuCamera = ref(null)



    // 隐藏摄像头管理
    const hiddenCameras = ref(new Set())

    // 设置摄像头点击事件
    const setupCameraClickEvents = () => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        // 添加实体选择变化监听
        viewer.selectedEntityChanged.addEventListener(() => {
            const selectedEntity = viewer.selectedEntity
            if (selectedEntity && selectedEntity.id && selectedEntity.id.startsWith('cam_')) {
                const camera = selectedEntity.cameraData // 直接从实体获取摄像头数据
                if (camera) {
                    selectedCamera.value = camera
                    console.log('选中摄像头:', camera.name)

                    // 不在这里打开视频播放器，避免重复调用
                    // 只在点击事件中打开视频播放器
                }
            }
        })

        // 添加左键点击事件处理
        viewer.cesiumWidget.screenSpaceEventHandler.setInputAction((event) => {
            // 隐藏右键菜单
            showContextMenu.value = false

            const pickedObject = viewer.scene.pick(event.position)
            console.log('点击事件触发，位置:', event.position)

            // 如果在新增摄像头模式下
            if (isAddingCameraMode.value) {
                const cartesian = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid)
                if (cartesian) {
                    const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
                    const longitude = Cesium.Math.toDegrees(cartographic.longitude)
                    const latitude = Cesium.Math.toDegrees(cartographic.latitude)
                    const height = cartographic.height

                    selectedPosition.value = {
                        longitude,
                        latitude,
                        height: height || 0
                    }

                    console.log('选择摄像头位置:', selectedPosition.value)

                    // 自动填入安装位置描述
                    newCameraForm.value.location = generateLocationDescription(longitude, latitude, height || 0)

                    // 在选择的位置添加临时标记
                    addTemporaryMarker(longitude, latitude, height || 0)

                    // 恢复鼠标样式
                    viewer.canvas.style.cursor = 'default'

                    // 显示对话框
                    showAddCameraDialog.value = true

                    console.log('位置选择完成，显示摄像头信息对话框')
                }
                return
            }

            if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
                const entity = pickedObject.id

                if (entity.id && entity.id.startsWith('cam_')) {
                    const camera = entity.cameraData // 直接从实体获取摄像头数据
                    if (camera) {
                        selectedCamera.value = camera
                        viewer.selectedEntity = entity
                        console.log('点击摄像头:', camera.name)

                        // 直接打开视频播放器，不显示信息框
                        if (videoPlayer && videoPlayer.openVideoPlayer) {
                            showCameraInfo.value = false // 确保不显示信息框
                            videoPlayer.openVideoPlayer(camera)
                        }
                    }
                }
            } else {
                // 点击空白区域，隐藏信息框
                showCameraInfo.value = false
                selectedCamera.value = null
                viewer.selectedEntity = undefined
                console.log('点击空白区域，隐藏信息框')
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

        // 添加右键点击事件处理（显示菜单）
        viewer.cesiumWidget.screenSpaceEventHandler.setInputAction((event) => {
            console.log('右键事件触发，位置:', event.position)
            const pickedObject = viewer.scene.pick(event.position)
            console.log('右键拾取对象:', pickedObject)

            if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id)) {
                const entity = pickedObject.id
                console.log('右键实体:', entity.id, entity)

                if (entity.id && entity.id.startsWith('cam_')) {
                    const camera = entity.cameraData
                    if (camera) {
                        console.log('显示摄像头右键菜单:', camera.name)

                        // 计算菜单位置（相对于页面）
                        const canvas = viewer.cesiumWidget.canvas
                        const canvasRect = canvas.getBoundingClientRect()

                        contextMenuCamera.value = camera
                        contextMenuPosition.value = {
                            x: canvasRect.left + event.position.x,
                            y: canvasRect.top + event.position.y
                        }

                        console.log('菜单位置:', contextMenuPosition.value)
                        showContextMenu.value = true
                    }
                }
            } else {
                // 右键点击空白区域，隐藏菜单
                console.log('右键点击空白区域，隐藏菜单')
                showContextMenu.value = false
            }
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

        // 禁用Cesium画布上的浏览器右键菜单
        viewer.cesiumWidget.canvas.addEventListener('contextmenu', (e) => {
            e.preventDefault()
            return false
        })

        console.log('摄像头点击事件已设置')
    }

    // 清除所有摄像头标记
    const clearAllCameraMarkers = () => {
        console.log('清除所有摄像头标记')
        const viewer = cesiumUtils.getViewer()
        if (!viewer) {
            console.error('Viewer未初始化，无法清除摄像头标记')
            return
        }
        viewer.entities.removeAll()
    }

    // 添加摄像头标记
    const addCameraMarkers = (cameras) => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) {
            console.warn('Viewer未初始化，无法添加摄像头标记')
            return
        }

        const camerasToAdd = cameras || cameraList3D.value
        clearAllCameraMarkers()

        console.log('添加摄像头标记，数量:', camerasToAdd.length)

        // 获取当前的3D模型tileset
        const tileset = cesiumUtils.getCurrentTileset()

        camerasToAdd.forEach(camera => {
            if (!camera.position.lng || !camera.position.lat) {
                console.warn(`摄像头 ${camera.id} 坐标无效:`, camera.position)
                return
            }

            const cameraIcon = createCameraIcon(camera.status)

            console.log(`添加摄像头标记: ${camera.name} at (${camera.position.lng}, ${camera.position.lat}, ${camera.position.height})`)

            // 创建固定位置的摄像头标记
            const position = Cesium.Cartesian3.fromDegrees(
                camera.position.lng,
                camera.position.lat,
                camera.position.height
            )

            const entity = viewer.entities.add({
                id: camera.id.toString().startsWith('cam_') ? camera.id : `cam_${camera.id}`, // 确保ID以cam_开头，但避免重复前缀
                name: camera.name,
                cameraData: camera, // 直接存储摄像头数据
                position: position,
                billboard: {
                    image: cameraIcon,
                    width: 40,
                    height: 40,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    sizeInMeters: false // 使用像素大小，不受距离影响
                },
                label: {
                    text: camera.name,
                    font: '14pt sans-serif',
                    pixelOffset: new Cesium.Cartesian2(0, -50),
                    fillColor: Cesium.Color.WHITE,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 2,
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    showBackground: true,
                    backgroundColor: Cesium.Color.fromAlpha(Cesium.Color.BLACK, 0.7),
                    backgroundPadding: new Cesium.Cartesian2(8, 4),
                    scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
            })
        })
    }

    // 添加单个摄像头标记
    const addSingleCameraMarker = (camera) => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) {
            console.warn('Viewer未初始化，无法添加摄像头标记')
            return
        }

        if (!camera.position.lng || !camera.position.lat) {
            console.warn(`摄像头 ${camera.id} 坐标无效:`, camera.position)
            return
        }

        const cameraIcon = createCameraIcon(camera.status)
        const tileset = cesiumUtils.getCurrentTileset()

        console.log(`添加单个摄像头标记: ${camera.name} at (${camera.position.lng}, ${camera.position.lat}, ${camera.position.height})`)

        // 创建固定位置的摄像头标记
        const position = Cesium.Cartesian3.fromDegrees(
            camera.position.lng,
            camera.position.lat,
            camera.position.height
        )

        // 确保ID格式正确，避免重复前缀
        const entityId = camera.id.toString().startsWith('cam_') ? camera.id : `cam_${camera.id}`

        const entity = viewer.entities.add({
            id: entityId,
            name: camera.name,
            cameraData: camera, // 直接存储摄像头数据
            position: position,
            billboard: {
                image: cameraIcon,
                width: 40,
                height: 40,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                sizeInMeters: false // 使用像素大小，不受距离影响
            },
            label: {
                text: camera.name,
                font: '14pt sans-serif',
                pixelOffset: new Cesium.Cartesian2(0, -50),
                fillColor: Cesium.Color.WHITE,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                showBackground: true,
                backgroundColor: Cesium.Color.fromAlpha(Cesium.Color.BLACK, 0.7),
                backgroundPadding: new Cesium.Cartesian2(8, 4),
                scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            }
        })
    }

    // 创建摄像头图标
    const createCameraIcon = (status) => {
        const color = getStatusColor(status)
        const svg = `
      <svg width="40" height="40" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
            <feDropShadow dx="2" dy="2" stdDeviation="2" flood-color="rgba(0,0,0,0.3)"/>
          </filter>
        </defs>
        <circle cx="20" cy="20" r="18" fill="white" stroke="${color}" stroke-width="2" filter="url(#shadow)"/>
        <path d="M12 14h16v12H12z" fill="${color}"/>
        <circle cx="20" cy="20" r="4" fill="white"/>
        <circle cx="20" cy="20" r="2" fill="${color}"/>
        <rect x="28" y="18" width="4" height="4" fill="${color}"/>
        ${status === 'online' || status === 'created' ?
                '<circle cx="32" cy="12" r="3" fill="#00ff88"/>' :
                status === 'offline' ?
                    '<circle cx="32" cy="12" r="3" fill="#ff6b6b"/>' :
                    '<circle cx="32" cy="12" r="3" fill="#ffaa00"/>'
            }
      </svg>
    `
        return 'data:image/svg+xml;base64,' + btoa(svg)
    }

    // 飞到摄像头位置
    const flyToCamera = (camera) => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
                camera.position.lng,
                camera.position.lat,
                camera.position.height + 100
            ),
            orientation: {
                heading: 0,
                pitch: Cesium.Math.toRadians(-30),
                roll: 0
            },
            duration: 2.0
        })
    }

    // 选择摄像头
    const selectCamera = (camera) => {
        selectedCamera.value = camera
        flyToCamera(camera)
    }

    // 关闭摄像头信息框
    const closeCameraInfo = () => {
        console.log('关闭摄像头信息框')
        showCameraInfo.value = false
        selectedCamera.value = null
        const viewer = cesiumUtils.getViewer()
        if (viewer) {
            viewer.selectedEntity = undefined
        }
    }

    // 面板控制
    const togglePanel = () => {
        isPanelCollapsed.value = !isPanelCollapsed.value
    }

    // 新增摄像头相关方法
    const startAddingCamera = () => {
        isAddingCameraMode.value = true
        showAddCameraDialog.value = false

        const viewer = cesiumUtils.getViewer()
        if (viewer) {
            viewer.canvas.style.cursor = 'crosshair'
        }

        cesiumUtils.showSuccess('请在3D场景中点击选择摄像头安装位置')
        console.log('进入新增摄像头模式，请在3D场景中点击选择位置')
    }

    const checkCameraNameUnique = () => {
        const name = newCameraForm.value.name.trim()
        if (!name) {
            nameCheckMessage.value = null
            return
        }

        const existingCamera = cameraList3D.value.find(camera =>
            camera.name.toLowerCase() === name.toLowerCase()
        )

        if (existingCamera) {
            nameCheckMessage.value = {
                type: 'error',
                text: `名称"${name}"已存在，请使用其他名称`
            }
        } else {
            nameCheckMessage.value = {
                type: 'success',
                text: '名称可用'
            }
        }
    }

    const cancelAddCamera = () => {
        isAddingCameraMode.value = false
        isEditingCamera.value = false
        editingCameraId.value = null
        showAddCameraDialog.value = false
        selectedPosition.value = null

        // 重置表单
        newCameraForm.value = {
            name: '',
            location: '',
            rtsp_url: '',
            wvp_device_id: '',
            wvp_channel_id: '',
            description: '',
            ai_enabled: false
        }

        nameCheckMessage.value = null

        const viewer = cesiumUtils.getViewer()
        if (viewer) {
            const tempMarker = viewer.entities.getById('temp_camera_marker')
            if (tempMarker) {
                viewer.entities.remove(tempMarker)
            }
            viewer.canvas.style.cursor = 'default'
        }

        console.log('取消摄像头操作')
    }

    const updateCameraForm = (updateData) => {
        console.log('更新摄像头表单数据:', updateData)
        Object.assign(newCameraForm.value, updateData)
    }

    const confirmAddCamera = async () => {
        if (!canSaveCamera.value) {
            cesiumUtils.showError('请填写必要信息并选择位置')
            return
        }

        isAddingCamera.value = true

        try {
            const cameraData = {
                name: newCameraForm.value.name.trim(),
                location: newCameraForm.value.location.trim() || undefined,
                latitude: selectedPosition.value.latitude,
                longitude: selectedPosition.value.longitude,
                rtsp_url: newCameraForm.value.rtsp_url.trim(),
                wvp_device_id: newCameraForm.value.wvp_device_id.trim() || undefined,
                wvp_channel_id: newCameraForm.value.wvp_channel_id.trim() || undefined,
                description: newCameraForm.value.description.trim() || undefined,
                ai_enabled: newCameraForm.value.ai_enabled
            }

            if (isEditingCamera.value) {
                // 编辑模式
                console.log('更新摄像头数据:', cameraData)

                console.log('更新摄像头ID:', editingCameraId.value)
                const updatedCamera3D = await cameraStore.updateCameraAndGet3D(editingCameraId.value, cameraData)
                console.log('摄像头更新成功:', updatedCamera3D)

                // 更新列表中的摄像头
                const index = cameraList3D.value.findIndex(c => c.id === editingCameraId.value)
                if (index > -1) {
                    cameraList3D.value[index] = updatedCamera3D
                }

                // 更新场景中的标记
                const viewer = cesiumUtils.getViewer()
                if (viewer) {
                    // 使用3D格式的ID来查找和删除实体
                    const entityId = `cam_${editingCameraId.value}`
                    const entity = viewer.entities.getById(entityId)
                    if (entity) {
                        viewer.entities.remove(entity)
                        console.log('已删除旧的摄像头实体:', entityId)
                    }
                    addSingleCameraMarker(updatedCamera3D)
                }

                cesiumUtils.showSuccess(`摄像头 "${cameraData.name}" 更新成功`)

            } else {
                // 新增模式
                console.log('添加摄像头数据:', cameraData)

                const newCamera3D = await cameraStore.addCameraAndGet3D(cameraData)
                console.log('摄像头创建成功:', newCamera3D)

                cameraList3D.value.push(newCamera3D)

                const viewer = cesiumUtils.getViewer()
                if (viewer) {
                    const tempMarker = viewer.entities.getById('temp_camera_marker')
                    if (tempMarker) {
                        viewer.entities.remove(tempMarker)
                    }
                }

                addSingleCameraMarker(newCamera3D)
                cesiumUtils.showSuccess(`摄像头 "${cameraData.name}" 添加成功`)
            }

            cancelAddCamera()

        } catch (error) {
            console.error('操作摄像头失败:', error)

            let errorMessage = isEditingCamera.value ? '更新摄像头失败' : '添加摄像头失败'

            if (error && error.response && error.response.status === 400) {
                const detail = error.response && error.response.data && error.response.data.detail
                if (detail) {
                    if (detail.includes('已存在')) {
                        errorMessage = `摄像头名称"${newCameraForm.value.name}"已存在，请使用其他名称`
                    } else if (detail.includes('RTSP')) {
                        errorMessage = 'RTSP地址格式不正确，请检查地址格式'
                    } else {
                        errorMessage = detail
                    }
                } else {
                    errorMessage = '请检查输入信息是否正确'
                }
            } else if (error && error.response && error.response.status === 500) {
                errorMessage = '服务器内部错误，请稍后重试'
            } else if (error && error.message) {
                errorMessage = error.message
            }

            cesiumUtils.showError(errorMessage)
        } finally {
            isAddingCamera.value = false
        }
    }

    // 添加临时标记
    const addTemporaryMarker = (longitude, latitude, height) => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        const existingTemp = viewer.entities.getById('temp_camera_marker')
        if (existingTemp) {
            viewer.entities.remove(existingTemp)
        }

        viewer.entities.add({
            id: 'temp_camera_marker',
            name: '新摄像头位置',
            position: Cesium.Cartesian3.fromDegrees(longitude, latitude, height + 2),
            billboard: {
                image: createTemporaryCameraIcon(),
                width: 50,
                height: 50,
                heightReference: Cesium.HeightReference.NONE,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            label: {
                text: '新摄像头位置',
                font: '14pt sans-serif',
                pixelOffset: new Cesium.Cartesian2(0, -60),
                fillColor: Cesium.Color.YELLOW,
                outlineColor: Cesium.Color.BLACK,
                outlineWidth: 2,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                showBackground: true,
                backgroundColor: Cesium.Color.fromAlpha(Cesium.Color.BLACK, 0.7),
                backgroundPadding: new Cesium.Cartesian2(8, 4),
                heightReference: Cesium.HeightReference.NONE,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            }
        })
    }

    // 创建临时摄像头图标
    const createTemporaryCameraIcon = () => {
        const svg = `
      <svg width="50" height="50" viewBox="0 0 50 50" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <filter id="glow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
            <feMerge> 
              <feMergeNode in="coloredBlur"/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
        </defs>
        <circle cx="25" cy="25" r="22" fill="#ffeb3b" stroke="#ff9800" stroke-width="3" filter="url(#glow)"/>
        <path d="M15 20h20v15H15z" fill="#ff9800"/>
        <circle cx="25" cy="27.5" r="5" fill="#ffeb3b"/>
        <circle cx="25" cy="27.5" r="2.5" fill="#ff9800"/>
        <rect x="35" y="25" width="5" height="5" fill="#ff9800"/>
        <text x="25" y="45" text-anchor="middle" font-size="8" fill="#ff9800" font-weight="bold">NEW</text>
      </svg>
    `
        return 'data:image/svg+xml;base64,' + btoa(svg)
    }

    // 根据坐标生成位置描述
    const generateLocationDescription = (longitude, latitude, height) => {
        const h = height.toFixed(1)

        let nearbyCamera = null
        let minDistance = Infinity

        cameraList3D.value.forEach(camera => {
            if (camera.position && camera.position.lng && camera.position.lat) {
                const dlng = Math.abs(longitude - camera.position.lng)
                const dlat = Math.abs(latitude - camera.position.lat)
                const distance = Math.sqrt(dlng * dlng + dlat * dlat)

                if (distance < 0.001 && distance < minDistance) {
                    minDistance = distance
                    nearbyCamera = camera
                }
            }
        })

        let heightDesc = ''
        if (height > 100) {
            heightDesc = '高层'
        } else if (height > 50) {
            heightDesc = '中层'
        } else if (height > 20) {
            heightDesc = '低层'
        } else if (height > 5) {
            heightDesc = '地面设施'
        } else {
            heightDesc = '地面'
        }

        let areaDesc = ''
        if (longitude > 116.398) {
            areaDesc = '东区'
        } else if (longitude < 116.396) {
            areaDesc = '西区'
        } else {
            areaDesc = '中心区'
        }

        if (latitude > 39.910) {
            areaDesc += '北部'
        } else if (latitude < 39.908) {
            areaDesc += '南部'
        } else {
            areaDesc += '中部'
        }

        let description = `${areaDesc}${heightDesc}`

        if (nearbyCamera) {
            description += ` (靠近${nearbyCamera.name})`
        }

        description += ` - 高度${h}m`

        return description
    }

    // 右键菜单操作方法
    const hideContextMenu = () => {
        showContextMenu.value = false
        contextMenuCamera.value = null
    }

    const editCamera = (camera) => {
        console.log('编辑摄像头:', camera.name)
        hideContextMenu()

        // 填充编辑表单
        newCameraForm.value = {
            name: camera.name,
            location: camera.location || '',
            rtsp_url: camera.rtsp_url || '',
            wvp_device_id: camera.wvp_device_id || '',
            wvp_channel_id: camera.wvp_channel_id || '',
            description: camera.description || '',
            ai_enabled: camera.ai_enabled || false
        }

        selectedPosition.value = {
            longitude: camera.position.lng,
            latitude: camera.position.lat,
            height: camera.position.height
        }

        // 设置编辑模式
        isEditingCamera.value = true
        // 使用apiId作为真实的摄像头ID，如果没有则从cam_格式中提取
        editingCameraId.value = camera.apiId || (camera.id.startsWith('cam_') ? parseInt(camera.id.replace('cam_', '')) : camera.id)
        showAddCameraDialog.value = true

        cesiumUtils.showSuccess('进入编辑模式')
    }

    const deleteCamera = async (camera) => {
        console.log('删除摄像头:', camera.name)
        hideContextMenu()

        if (!confirm(`确定要删除摄像头"${camera.name}"吗？此操作不可撤销。`)) {
            return
        }

        try {
            cesiumUtils.isLoading.value = true
            cesiumUtils.loadingText.value = '正在删除摄像头...'

            // 提取真实的摄像头ID（去掉cam_前缀）和实体ID
            let realCameraId = camera.apiId || (camera.id.toString().startsWith('cam_') ? camera.id.replace('cam_', '') : camera.id)
            let entityId = camera.id.toString().startsWith('cam_') ? camera.id : `cam_${camera.id}`

            console.log('原始摄像头数据:', camera)
            console.log('真实摄像头ID:', realCameraId, '实体ID:', entityId)
            await cameraStore.deleteCamera(realCameraId)

            // 从列表中移除
            const index = cameraList3D.value.findIndex(c => c.id === camera.id)
            if (index > -1) {
                cameraList3D.value.splice(index, 1)
            }

            // 从场景中移除标记
            const viewer = cesiumUtils.getViewer()
            if (viewer) {
                const entity = viewer.entities.getById(entityId)
                if (entity) {
                    viewer.entities.remove(entity)
                    console.log('成功从场景中移除摄像头实体:', entityId)
                } else {
                    console.warn('未找到要删除的摄像头实体:', entityId)
                }
            }

            cesiumUtils.showSuccess(`摄像头"${camera.name}"已删除`)

        } catch (error) {
            console.error('删除摄像头失败:', error)
            cesiumUtils.showError('删除摄像头失败: ' + error.message)
        } finally {
            cesiumUtils.isLoading.value = false
        }
    }

    const toggleCameraVisibility = (camera) => {
        console.log('切换摄像头可见性:', camera.name, 'ID:', camera.id)
        hideContextMenu()

        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        // 确保使用正确的实体ID格式
        let entityId = camera.id
        if (!entityId.startsWith('cam_')) {
            entityId = `cam_${camera.id}`
        }

        console.log('查找实体ID:', entityId)
        const entity = viewer.entities.getById(entityId)
        if (entity) {
            entity.show = !entity.show
            console.log('实体显示状态:', entity.show)

            // 管理隐藏状态
            if (entity.show) {
                hiddenCameras.value.delete(entityId)
                cesiumUtils.showSuccess(`摄像头"${camera.name}"已显示`)
            } else {
                hiddenCameras.value.add(entityId)
                cesiumUtils.showSuccess(`摄像头"${camera.name}"已隐藏`)
            }
        } else {
            console.error('未找到摄像头实体:', entityId)
            cesiumUtils.showError('未找到摄像头实体')
        }
    }

    // 显示所有隐藏的摄像头
    const showAllHiddenCameras = () => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        let count = 0
        hiddenCameras.value.forEach(cameraId => {
            const entity = viewer.entities.getById(cameraId)
            if (entity) {
                entity.show = true
                count++
            }
        })

        hiddenCameras.value.clear()

        if (count > 0) {
            cesiumUtils.showSuccess(`已显示 ${count} 个隐藏的摄像头`)
        } else {
            cesiumUtils.showSuccess('没有隐藏的摄像头')
        }
    }

    // 隐藏所有摄像头
    const hideAllCameras = () => {
        const viewer = cesiumUtils.getViewer()
        if (!viewer) return

        let count = 0
        cameraList3D.value.forEach(camera => {
            const entity = viewer.entities.getById(camera.id)
            if (entity && entity.show) {
                entity.show = false
                hiddenCameras.value.add(camera.id)
                count++
            }
        })

        if (count > 0) {
            cesiumUtils.showSuccess(`已隐藏 ${count} 个摄像头`)
        }
    }

    const focusOnCamera = (camera) => {
        console.log('聚焦摄像头:', camera.name)
        hideContextMenu()
        flyToCamera(camera)
    }

    const playVideo = (camera) => {
        console.log('播放摄像头视频:', camera.name)
        hideContextMenu()
        if (videoPlayer && videoPlayer.openVideoPlayer) {
            videoPlayer.openVideoPlayer(camera)
        }
    }



    // 工具函数
    const getStatusColor = (status) => {
        switch (status) {
            case 'online': return '#00ff88'
            case 'created': return '#00ff88'  // 新创建的摄像头视为在线
            case 'offline': return '#ff6b6b'
            case 'maintenance': return '#ffaa00'
            default: return '#666'
        }
    }

    const getStatusText = (status) => {
        switch (status) {
            case 'online': return '在线'
            case 'created': return '已创建'
            case 'offline': return '离线'
            case 'maintenance': return '维护中'
            default: return '未知'
        }
    }

    const formatPosition = (position) => {
        if (!position) return '未设置'
        return `(${(position.lng && position.lng.toFixed(6)) || 0}, ${(position.lat && position.lat.toFixed(6)) || 0}, ${(position.height && position.height.toFixed(1)) || 0}m)`
    }

    return {
        // 响应式数据
        cameraList3D,
        selectedCamera,
        showCameraInfo,
        isPanelCollapsed,
        showAddCameraDialog,
        isAddingCameraMode,
        isAddingCamera,
        selectedPosition,
        nameCheckMessage,
        newCameraForm,
        canSaveCamera,
        showContextMenu,
        contextMenuPosition,
        contextMenuCamera,
        isEditingCamera,
        editingCameraId,

        // 方法
        loadCamerasFromAPI,
        setupCameraClickEvents,
        addCameraMarkers,
        clearAllCameraMarkers,
        addSingleCameraMarker,
        flyToCamera,
        selectCamera,
        closeCameraInfo,
        togglePanel,
        startAddingCamera,
        checkCameraNameUnique,
        cancelAddCamera,
        confirmAddCamera,
        updateCameraForm,
        getStatusText,
        formatPosition,

        // 右键菜单方法
        hideContextMenu,
        editCamera,
        deleteCamera,
        toggleCameraVisibility,
        focusOnCamera,
        playVideo,

        // 批量显示/隐藏方法
        showAllHiddenCameras,
        hideAllCameras,
        hiddenCameras
    }
}